package com.atguigu.flink.chapter06.state.keyed;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lzc
 * @Date 2023/6/20 14:23
 */
public class MapStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 输出每个传感器所有的不同水位
        
        env
            .socketTextStream("hadoop162", 8888)
            .map(new WaterSensorMapFunction())
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
    
                private MapState<Integer, Object> mapState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    mapState = getRuntimeContext()
                        .getMapState(
                            new MapStateDescriptor<Integer, Object>("vcs", Integer.class, Object.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    mapState.put(value.getVc(), new Object());
                    
                    // 取出 map 状态中所有的 key
                    Iterable<Integer> it = mapState.keys();
                    List<Integer> list = AtguiguUtil.toList(it);
    
                    out.collect(ctx.getCurrentKey() + " 的所有不重复的水位: " + list);
    
                    
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
mapState.put(key, value); 添加或者更新
mapState.keys() 获取所有的 key
mapState.putAll(map 集合) 添加或者更新 多个 k-v
mapState.values() 获取所有的 value
mapState.remove(key) 移除指定的 key
mapState.contains(key) 判断指定的 key 是否存在
mapState.entries()  获取所有的key-value 对
 */